package dao;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.sql.Blob;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import beans.Task;
import db.DBDruidManager;
import engine.BIEngine0_1.TaskThread;

public class TaskDao {
	private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	
	//查询任务通过taskid
		public List<Object> getTaskById(String taskId){
			String sql = "select * from task, user where task.create_person = user.user_id and task_id = ?" ;
			Object[] params = new Object[]{taskId};
			List<Object> tasks = new ArrayList<>();
	        tasks = Query.executeQueryList(tasks, sql, params, new QueryCallBackList() {
	            @Override
	            public List<Object> doExecuteList(ResultSet rs, List<Object> results) {
	                try {
	                    while (rs.next()) {
	                        Task t = new Task(rs.getInt("task_id"), rs.getInt("model_id"),rs.getString("name"), 
	                                rs.getString("user_name"), rs.getString("start_time"),rs.getString("end_time"),
	                                rs.getString("json"), rs.getBoolean("is_nesting"), rs.getString("nest_json"), rs.getString("introduction"),
	                                rs.getString("statement"));
	                        t.setUserId(rs.getString("user_id"));
	                        results.add(t);
	                    }
	                } catch (SQLException e) {
	                    e.printStackTrace();
	                }
	                return results;
	            }
	        });
//	        Task t = (Task)tasks.get(0);
	        return tasks;
	  }
	//不需要id，这是直接查询所有任�
    public List<Object> getTaskByTaskId(){
		String sql = "select task_id,model_name,name,user.user_name,start_time,end_time,is_nesting,introduction,statement from task, user where task.create_person = user.user_id" ;
		Object[] params = new Object[]{};
		List<Object> tasks = new ArrayList<>();
        tasks = Query.executeQueryList(tasks, sql, null, new QueryCallBackList() {
            @Override
            public List<Object> doExecuteList(ResultSet rs, List<Object> results) {
                try {
                    while (rs.next()) {
                        Task t = new Task(rs.getInt("task_id"), rs.getInt("model_id"),rs.getString("name"), 
                                rs.getString("user_name"), rs.getString("start_time"),rs.getString("end_time"),
                                null, false, null, rs.getString("introduction"),
                                rs.getString("statement"));
                        results.add(t);
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                return results;
            }
        });
        return tasks;
  }
    //分页查询任务
    public List<Object> getTasks(Integer onePageCount,Integer currentPage){
    	String sql = "select task_id,model_name,name,user_name,start_time,end_time,task.introduction,statement from task, user,model where task.create_person = user.user_id and model.model_id=task.model_id order by task_id desc limit "+(currentPage - 1) * onePageCount + " , " +onePageCount;
    	List<Object> tasks = new ArrayList<>();
    	tasks = Query.executeQueryList(tasks, sql, null, new QueryCallBackList(){
               @Override
               public List<Object> doExecuteList(ResultSet rs, List<Object> results) {
                   try {
                       while (rs.next()) {//format.format(rs.getTimestamp("end_time")),
                           Task t = new Task(rs.getInt("task_id"), rs.getString("model_name"),rs.getString("name"),
                                   rs.getString("user_name"), rs.getString("start_time"),rs.getString("end_time"),
                                  null, false, null, rs.getString("introduction"),
                                   rs.getString("statement"));
                           results.add(t);
                       }
                   } catch (SQLException e) {
                       e.printStackTrace();
                   }
                   return results;
               }
           });
           return tasks;
     }
	public List<Object> addTask(Task t){
		int modelId = t.getModel_id();
		String name = t.getName();
		String createPerson = t.getCreate_person();
		String json = t.getJson();
		boolean isNesting = t.isIs_nesting();
		String nestJson =t.getNest_json();
		String introduction = t.getIntroduction();
		String sql = "insert into task (model_id,name,create_person,json,is_nesting,nest_json,introduction) values (?,?,?,?,?,?,?)";
		Object[] params = new Object[]{modelId,name,createPerson,json,isNesting,nestJson,introduction,};
		List<Object> results = new ArrayList<>();
		results = Query.executeDMLwithGeneratedKeys(results, sql, params, new QueryCallBackList() {
			
			@Override
			public List<Object> doExecuteList(ResultSet rs, List<Object> results) {
				try {
					while(rs.next()){
						results.add(Integer.valueOf(rs.getInt(1)));
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}
				return results;
			}
		});
		if (results.size() > 0)

		{
			return results;
		} else

		{
			return null;
		}
	}

   public boolean deteleTaskByTaskId(String taskId){
	   String sql = "delete from task where task_id='" + taskId + "'";
	   Object[] params = new Object[]{taskId};
	   int result = Query.executeDML(sql,null);
	   if(result==-1){
		   return false;
	   }
	   else {
           return true;
       }
   }
   /**
    * 根据每页数量计算总页� By朱��
    *
    * @param onePageCount
    * @return
    */
   public int getTaskPageNum(Integer onePageCount){
	   int taskNum = this.getTaskPageNum();
	   return (taskNum % onePageCount)==0? (taskNum / onePageCount) : (taskNum / onePageCount + 1);
   }
   /**
    * 获取�有的算法数量
    *
    * @return
    */
   public synchronized int getTaskPageNum() {
       String sql = "select count(*) from task";
      return PublicDao.oneNum(sql,null);
   }
   public List<Object> findTaskByTaskId(int taskId){
		String sql = "select * from task, user where task.create_person=user.user_id task_id='"+taskId+"'" ;
		Object[] params = new Object[]{};
		List<Object> tasks = new ArrayList<>();
      tasks = Query.executeQueryList(tasks, sql, null, new QueryCallBackList() {
          @Override
          public List<Object> doExecuteList(ResultSet rs, List<Object> results) {
              try {
                  while (rs.next()) {
                      /*Task t = new Task(rs.getInt("task_id"), rs.getInt("model_id"),rs.getString("name"), 
                              rs.getString("user_name"), rs.getString("start_time"),rs.getString("end_time"),
                              rs.getString("json"), rs.getBoolean("is_nesting"), rs.getString("nest_json"), rs.getString("introduction"),
                              rs.getString("statement"));*/
                	  Task t = new Task(rs.getInt("task_id"), rs.getInt("model_id"),rs.getString("name"), 
                              rs.getString("user_name"), rs.getString("start_time"),rs.getString("end_time"),
                              null, rs.getBoolean("is_nesting"), null, rs.getString("introduction"),
                              rs.getString("statement"));
                      results.add(t);
                  }
              } catch (SQLException e) {
                  e.printStackTrace();
              }
              return results;
          }
      });
      return tasks;
   }
	public boolean serializeTask2DB(TaskThread taskThread)
	{
		String sql = "update history_task set pause_info=? where task_hash=?";
		Object[] params = {taskThread,taskThread.runningTaskBean.getTaskHash()};
		return Query.executeDML(sql,params)>0;
	}

	public TaskThread getTaskThread(String taskHash){
		TaskThread result = null;
		String sql="select pause_info from history_task where task_hash =?";
		Object[] params = {taskHash};
		return (TaskThread) Query.executeQueryObject(sql, params, new QueryCallBack() {
			@Override
			public Object doExecute(ResultSet rs) {
				TaskThread result = null;
				try {
					while(rs.next()){
						Blob inBlob=rs.getBlob(1);                             //获取blob对象
						InputStream is=inBlob.getBinaryStream();                //获取二进制流对象
						BufferedInputStream bis=new BufferedInputStream(is);    //带缓冲区的流对象
						byte[] buff=new byte[(int) inBlob.length()];
						while(-1!=(bis.read(buff, 0, buff.length))){            //一次性全部读到buff中
							ObjectInputStream in=new ObjectInputStream(new ByteArrayInputStream(buff));
							result =(TaskThread)in.readObject();                   //读出对象
						}
					}
				} catch (SQLException | IOException | ClassNotFoundException e) {
					e.printStackTrace();
				}
				return result;
			}
		});
	}


	/**
	 * 获取因为tomcat关闭而序列化到数据库的任务
	 */
	public List<Object> getDisconnectTaskThread(){
		String sql="select pause_info from history_task where not isnull(pause_info) and statement!='pause' and statement!='finished' and statement!='stopped'";
		List<Object> taskThreads = new ArrayList<>();
		return  Query.executeQueryList(taskThreads, sql, new Object[]{}, new QueryCallBackList() {
			@Override
			public List<Object> doExecuteList(ResultSet rs, List<Object> results) {
				try {
					while(rs.next()){
						TaskThread result = null;
						Blob inBlob=rs.getBlob(1);                             //获取blob对象
						InputStream is=inBlob.getBinaryStream();                //获取二进制流对象
						BufferedInputStream bis=new BufferedInputStream(is);    //带缓冲区的流对象
						byte[] buff=new byte[(int) inBlob.length()];
						while(-1!=(bis.read(buff, 0, buff.length))){            //一次性全部读到buff中
							ObjectInputStream in=new ObjectInputStream(new ByteArrayInputStream(buff));
							result =(TaskThread)in.readObject();                   //读出对象
						}
						results.add(result);
					}
				} catch (SQLException | IOException | ClassNotFoundException e) {
					e.printStackTrace();
				}
				return results;
			}
		});
	}
	public boolean updateJsonPath(String path,int id)
	{
		String sql = "update task set json=? where task_id=?";
		Object[] params = {path,id};
		return Query.executeDML(sql,params)>0;
	}
	
	public static int getCurrentTask(int modelId){
		String sql = "SELECT max(task_id) as taskid FROM task WHERE  model_id=?";
		Object[] params = {modelId};
		return (int) Query.executeQueryObject(sql, params, new QueryCallBack() {
			@Override
			public Object doExecute(ResultSet rs) {
				int result = 0;
				try {
					while(rs.next()){
						result = rs.getInt("taskid");
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}
				return result;
			}
		});
	}
}